package com.example.java_gobang.api;

import com.example.java_gobang.model.User;
import com.example.java_gobang.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author hanzishuai
 * @date 2025/03/01 10:25
 * @Description
 */
@Slf4j
@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {

        if (!StringUtils.hasLength(username)) {
            log.warn("参数校验失败，username ：{}", username);
            return new User();
        }

        User user = userMapper.selectByName(username);

        if (password == null || user == null || !password.equals(user.getPassword())) {
            log.warn("参数校验失败，username：{}，password ：{}", username, password);
            return new User();
        }

        // 创建一个 Session
        HttpSession httpSession = req.getSession(true);
        httpSession.setAttribute("user", user);
        log.info("username = {}，用户已登陆", username);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(@RequestParam("username") String username, @RequestParam("password") String password) {
        if(!StringUtils.hasLength(password)) {
            return new User();
        }
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            log.info("注册成功，username = {}", username);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            // 用户名已存在，插入失败
            User user = new User();
            log.warn("用户名已存在，username ：{}", username);
            return user;
        }

    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        try {
            // Session 存在继续往下运行，Session 不存在会报空指针异常
            HttpSession httpSession = req.getSession(false);

            User user = (User) httpSession.getAttribute("user");
            // 去数据库中查找
            User newUser = userMapper.selectByName(user.getUsername());
            log.info("返回用户信息，username = {}", user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            log.warn("Session 不存在");
            // Session 不存在时
            return new User();
        }
    }
}
























